package com.sk.helper.page;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Paint;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.sk.helper.R;
import com.sk.helper.base.BaseFragment;
import com.sk.helper.data.FaceButton;
import com.sk.helper.data.Rules;
import com.sk.helper.service.ConnectionService;
import com.sk.helper.service.DeviceService;
import com.sk.helper.utils.Protocol;

import java.lang.reflect.Method;
import java.util.Set;

import io.realm.Realm;
import io.realm.RealmBaseAdapter;
import io.realm.RealmResults;

/**
 * Created by wq on 2017/1/20.
 * 作用：主页面
 */

public class HomeFragment extends BaseFragment {


    private static final String TAG = HomeFragment.class.getSimpleName();
    private BluetoothAdapter mBluetoothAdapter = null;
    //private TextView tv_state_device;
    private boolean connectState = false;
    public DeviceService deviceService;

    private TextView tv_state_device;
    private Button button_map;
    private ListView listView;
    private Realm realm;
    private ConnectionService.Binder myBinder = null;

/*    static final int UP = 0;
    static final int DOWN = 1;*/

    /**
     * 返回的数据
     */
    @Override
    public View initView() {

        View view = View.inflate(mContext, R.layout.homefragment, null);
        //Log.e("TAG","   DEV -- "+ mBluetoothAdapter.getProfileConnectionState(4));
        // Log.e("TAG","   DEV -- "+ mBluetoothAdapter.getConnectionState());
        tv_state_device = view.findViewById(R.id.tv_state_device);

        listView = (ListView) view.findViewById(android.R.id.list);
        realm = Realm.getDefaultInstance();
        RealmResults<Rules> ruleList = realm.where(Rules.class).findAll();
        Adapter adapter = new Adapter(mContext, ruleList, true);
        listView.setAdapter(adapter);


        button_map = view.findViewById(R.id.button_map);
        button_map.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("----home---", "--onclick---------");
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //如果是服务里调用，必须加入new task标识
                intent.addCategory(Intent.CATEGORY_HOME);
                startActivity(intent);


                Intent service = new Intent(mContext, ConnectionService.class);
                mContext.bindService(service, conn, Context.BIND_AUTO_CREATE);
                service.setAction(ConnectionService.ACTION_SHOW_PANEL);
                mContext.startService(service);


            }
        });
        initBluetooth();
        Log.e("tag", "HomeFragment mcontext = " + mContext);
        return view;

    }

    private void initBluetooth() {

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(mContext, getString(R.string.no_device), Toast.LENGTH_LONG).show();
            return;
        }

// 设置广播信息过滤
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);

        intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);

// 注册广播接收器，接收并处理搜索结果


        mContext.registerReceiver(mReceiver, intentFilter);
        mBluetoothAdapter.startDiscovery();

        if (mBluetoothAdapter.getProfileConnectionState(4) == 0) {
            tv_state_device.setText(getString(R.string.unconnected));
            tv_state_device.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
            tv_state_device.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openSetting();
                }
            });
        } else {
            // tv_model.setText(getString(R.string.connected)+device.getName());
            Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
            //Intent intent = new Intent();
            Log.e("TAG", "   DEV -111- " + devices.size());
            connectState = true;
            for (int i = 0; i < devices.size(); i++) {
                BluetoothDevice device = devices.iterator().next();

                Log.e("TAG", "   DEV -- " + device.getAddress());
                tv_state_device.setText(getString(R.string.connected) + device.getName());
                tv_state_device.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
            }
        }
    }

    private void openSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_BLUETOOTH_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException ex) {
            ex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //Log.e("TAG", "--" + action);
            // When discovery finds a device
            BluetoothDevice device;
            device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            switch (intent.getAction()) {
                case BluetoothDevice.ACTION_ACL_CONNECTED:
                    Log.e("heomefragment", "----sk--  device.getAddress()==---- " + device.getAddress());
                    connectState = true;
                    tv_state_device.setText(getString(R.string.connected) + device.getName());
                    tv_state_device.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
                    break;

                case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                    connectState = false;
                    tv_state_device.setText(getString(R.string.unconnected));
                    tv_state_device.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
                    /*tv_model.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            openSetting();
                        }
                    });*/
                    break;

            }
        }
    };

    @Override
    public void initData() {
        super.initData();
        //设置标题
        //tv_title.setText("主页面标题");
        Log.e("----------111", "主页面数据被初始化了.1...");
        //if (connectState) {
        deviceService = new DeviceService(mContext, mHandler);
        //}

        //  rg_select.check(R.id.rb_modify);
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e("1111", "onresume-----");


        Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象

        if (mBluetoothAdapter.getProfileConnectionState(4) == 0) {
            tv_state_device.setText(getString(R.string.unconnected));
            tv_state_device.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
            tv_state_device.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openSetting();
                }
            });
        } else {

            try {//得到连接状态的方法
                Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
                //打开权限
                method.setAccessible(true);
                int state = (int) method.invoke(mBluetoothAdapter, (Object[]) null);

                if (state == BluetoothAdapter.STATE_CONNECTED) {
                    Log.e("BLUETOOTH", "BluetoothAdapter.STATE_CONNECTED");
                    Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
                    Log.e("BLUETOOTH", "devices:" + devices.size());

                    for (BluetoothDevice device : devices) {
                        Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                        method.setAccessible(true);
                        boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);
                        if (isConnected) {
                            Log.e("BLUETOOTH", "connected:" + device.getName());
                            // deviceList.add(device);
                            deviceService.connect(device);
                            tv_state_device.setText(getString(R.string.connected) + device.getName());
                            tv_state_device.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


    // The Handler that gets information back from the BluetoothChatService

    @Override
    public void onDestroy() {
        super.onDestroy();

        //Log.e(TAG, "onDestroy--  hhh ffffffffff");
    }

    public class Adapter extends RealmBaseAdapter<Rules> {

        public Adapter(Context context, RealmResults<Rules> realmResults, boolean automaticUpdate) {
            super(context, realmResults, automaticUpdate);
            Log.e("----home---", "--7--------");

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Log.e("----home---", "--8--------");
            if (convertView == null) {
                //convertView = getLayoutInflater().inflate(R.layout.rules_item, null);
                convertView = LayoutInflater.from(mContext).inflate(R.layout.rules_item, null);
            }

            String str = "";
            int i = 0;
            for (FaceButton faceButton : realmResults.get(position).getFaceButtons()) {
                str += faceButton.getKey() + " (" + faceButton.getX() + "," + faceButton.getY() + ")";

                if (i < realmResults.get(position).getFaceButtons().size() - 1) {
                    str += " | ";
                }
                i++;
            }

            TextView rules = (TextView) convertView.findViewById(R.id.rules);
            rules.setText(str);

            return convertView;
        }
    }


    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String keyText = "";
            int tmpValue = 0;
            Log.e(TAG, "msg.what=--: " + msg.what);

            switch (msg.what) {
                case Protocol.MESSAGE_KEY:

                    int read_value = (int) msg.obj;
                    Log.e(TAG, "msg.arg1==" + msg.arg1 + "read_value=: " + read_value);

                    if (myBinder != null) {
                        if (msg.arg1 == Protocol.KEYDOWN) {
                            Log.e(TAG, "发送数据 ---down-."+read_value);
                            myBinder.setData(Protocol.KEYDOWN, read_value);
                        } else {
                            Log.e(TAG, "发送数据 ---up-."+read_value);
                            myBinder.setData(Protocol.KEYUP, read_value);
                        }
                    }
                    /*if (msg.arg1 == Protocol.KEYDOWN) {
                        switch (read_value) {
                            case Protocol.KEYCODE_BUTTON_A:
                                Log.e(TAG, "msg.arg1==aaaaa down");
                                if (myBinder != null) {
                                    Log.e(TAG, "发送数据 ----.");
                                    myBinder.setData(DOWN,read_value);
                                }
                                break;
                            case Protocol.KEYCODE_BUTTON_B:

                                // tmpValue = Protocol.KEYCODE_BUTTON_A;
                                Log.e(TAG, "msg.arg1==bbbbb down");
                                if (myBinder != null) {
                                    Log.e(TAG, "发送数据 ----.");
                                    myBinder.setData(DOWN,100);
                                }
                                break;
                            }
                    } else {
                        switch (read_value) {
                            case Protocol.KEYCODE_BUTTON_A:
                                Log.e(TAG, "msg.arg1==aaaaa up");
                                if (myBinder != null) {
                                    Log.e(TAG, "发送数据 ----.");
                                    myBinder.setData(UP,read_value);
                                }
                                break;
                            case Protocol.KEYCODE_BUTTON_B:
                                Log.e(TAG, "msg.arg1==bbbbb up");
                                if (myBinder != null) {
                                    Log.e(TAG, "发送数据 ----.");
                                    myBinder.setData(UP,read_value);
                                }
                                break;
                        }
                    }*/
            }
        }
    };

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder iBinder) {
            Log.e(TAG, "onServiceConnected called.");
            myBinder = (ConnectionService.Binder) iBinder;//②
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };


}
